/**
 * 测试脚本：验证删除项目时是否同时删除上传模型缓存
 * 
 * 使用方法：
 * node backend/test-delete-cache.js
 */

const path = require('path');
const fs = require('fs').promises;

const PROJECTS_DIR = path.join(__dirname, '../projects');

/**
 * 检查项目和缓存目录
 */
async function checkProjectAndCache(projectPath) {
    const projectDir = path.join(PROJECTS_DIR, projectPath);
    const cacheDir = path.join(PROJECTS_DIR, 'cache', 'uploadmodel', projectPath);
    
    const results = {
        projectExists: false,
        cacheExists: false
    };
    
    try {
        await fs.access(projectDir);
        results.projectExists = true;
    } catch (error) {
        // 目录不存在
    }
    
    try {
        await fs.access(cacheDir);
        results.cacheExists = true;
    } catch (error) {
        // 目录不存在
    }
    
    return results;
}

/**
 * 主测试函数
 */
async function testDeleteCache() {
    console.log('🧪 开始测试删除项目缓存功能...\n');
    
    try {
        // 读取项目索引
        const indexPath = path.join(PROJECTS_DIR, 'projects.json');
        const indexData = await fs.readFile(indexPath, 'utf-8');
        const index = JSON.parse(indexData);
        
        console.log('📋 当前项目列表:');
        for (const project of index.projects || []) {
            const status = await checkProjectAndCache(project.path);
            console.log(`  - ${project.name} (${project.id})`);
            console.log(`    项目目录: ${status.projectExists ? '✅ 存在' : '❌ 不存在'}`);
            console.log(`    缓存目录: ${status.cacheExists ? '✅ 存在' : '⚪ 不存在'}`);
        }
        
        console.log('\n📋 回收站项目列表:');
        if (index.recycleBin && index.recycleBin.length > 0) {
            for (const project of index.recycleBin) {
                const status = await checkProjectAndCache(project.path);
                console.log(`  - ${project.name} (${project.id})`);
                console.log(`    项目目录: ${status.projectExists ? '✅ 存在' : '❌ 不存在'}`);
                console.log(`    缓存目录: ${status.cacheExists ? '✅ 存在' : '⚪ 不存在'}`);
                
                const deletedDate = new Date(project.deletedAt);
                const daysAgo = Math.floor((new Date() - deletedDate) / (1000 * 60 * 60 * 24));
                console.log(`    删除时间: ${deletedDate.toLocaleString('zh-CN')} (${daysAgo}天前)`);
            }
        } else {
            console.log('  (回收站为空)');
        }
        
        console.log('\n✅ 测试完成！');
        console.log('\n💡 提示：');
        console.log('  - 当项目被彻底删除时，缓存目录也会被自动删除');
        console.log('  - 清理过期项目（30天前）时，也会删除对应的缓存目录');
        
    } catch (error) {
        console.error('❌ 测试失败:', error);
    }
}

// 运行测试
testDeleteCache();

